var app = new Vue({
    el: '#app',
    data: {
        list: [{
            id: 1,
            name: '小米手机',
            category: '数码类',
            price: 9999,
            count: 1
        }, {
            id: 2,
            name: '花花公子夏日短袖',
            category: '服装类',
            price: 699,
            count: 1
        }, {
            id: 3,
            name: '格力空调',
            category: '电器类',
            price: 3999,
            count: 1
        }],
        checkbox: [],
        checkAll: false,
    },
    computed: {
        totalPrice: function () {
            var total = 0;
            for (var i = 0; i < this.checkbox.length; i++) {
                var item = this.checkbox[i];
                total += item.price * item.count;
            }
            return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
        }
    },
    methods: {
        handleReduce: function (index) {
            if (this.list[index].count === 1) return; //保证商品至少有一个
            this.list[index].count--;
        },
        handleAdd: function (index) {
            this.list[index].count++;
        },
        handleRemove: function (index) {
            this.list.splice(index, 1);
        },
        changeAllChecked: function () {
            if (this.checkAll) {
                this.checkbox = [];
            } else {
                this.checkbox = [];
                this.list.forEach(element => {
                    this.checkbox.push(element);
                });
            }
            console.log(this.checkbox);
        },
    },
    watch: {
        'checkbox': {
            handler: function (val, oldVal) {
                if (val.length === this.list.length) {
                    this.checkAll = true;
                } else {
                    this.checkAll = false;
                }
            },
            deep: true
        }
    }
});